import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Typography, Button, message, Modal } from 'antd';
import AnimatedDice from './AnimatedDice';
import './LegalConceptPuzzle.css';

const { Title, Text } = Typography;

// 法律概念拼接游戏组件
const LegalConceptPuzzle = ({ 
  onComplete = () => {}, 
  onEarnDice = () => {},
  isLoadingComplete = false,
  conceptBank = []
}) => {
  // 游戏状态
  const [currentConcept, setCurrentConcept] = useState(null);
  const [fragments, setFragments] = useState([]);
  const [selectedFragments, setSelectedFragments] = useState([]);
  const [completedRounds, setCompletedRounds] = useState(0);
  const [gameActive, setGameActive] = useState(true);
  const [showCongrats, setShowCongrats] = useState(false);
  const [earnedDice, setEarnedDice] = useState(0);
  const [usedConceptIndices, setUsedConceptIndices] = useState([]);
  const [showHint, setShowHint] = useState(false); // 是否显示提示
  const [correctOrder, setCorrectOrder] = useState([]); // 正确的顺序

  // 初始化游戏 - 随机打乱概念库顺序
  useEffect(() => {
    if (conceptBank.length > 0 && gameActive) {
      // 创建概念库的随机顺序
      const randomizedConceptIndices = [...Array(conceptBank.length).keys()]
        .sort(() => Math.random() - 0.5);
      
      // 记录随机顺序
      console.log('随机概念顺序:', randomizedConceptIndices);
      
      // 设置已使用的概念索引为空，以便使用新的随机顺序
      setUsedConceptIndices([]);
      
      // 重置提示状态
      setShowHint(false);
      
      startNewRound();
    }
  }, [conceptBank, gameActive]);
  
  // 监听加载完成状态
  useEffect(() => {
    if (isLoadingComplete) {
      // 当题库加载完成时，可以显示提示按钮
      console.log('题库加载完成，可以显示提示按钮');
    }
  }, [isLoadingComplete]);

  // 检查加载是否完成
  useEffect(() => {
    if (isLoadingComplete && !gameActive && completedRounds > 0) {
      // 如果加载完成且游戏已结束，则触发完成回调
      setTimeout(() => {
        onComplete();
      }, 2000); // 给玩家2秒时间查看结果
    }
  }, [isLoadingComplete, gameActive, completedRounds, onComplete]);

  // 开始新一轮游戏
  const startNewRound = useCallback(() => {
    if (conceptBank.length === 0) return;
    
    // 重置提示状态
    setShowHint(false);
    
    // 找出未使用过的概念索引
    const availableIndices = conceptBank
      .map((_, index) => index)
      .filter(index => !usedConceptIndices.includes(index));
    
    // 如果所有概念都已使用过，则重置已使用列表
    let newUsedIndices = [...usedConceptIndices];
    let randomIndex;
    
    if (availableIndices.length === 0) {
      randomIndex = Math.floor(Math.random() * conceptBank.length);
      newUsedIndices = [randomIndex];
    } else {
      // 从未使用过的概念中随机选择一个
      const randomAvailableIndex = Math.floor(Math.random() * availableIndices.length);
      randomIndex = availableIndices[randomAvailableIndex];
      newUsedIndices.push(randomIndex);
    }
    
    setUsedConceptIndices(newUsedIndices);
    const selectedConcept = conceptBank[randomIndex];
    setCurrentConcept(selectedConcept);
    
    // 先创建带有正确顺序信息的碎片数组
    const fragmentsWithOrder = selectedConcept.fragments.map((fragment, index) => ({
      id: index,
      text: fragment,
      // 使用correctOrder数组中的值减1作为originalOrder，因为correctOrder是从1开始的
      originalOrder: (selectedConcept.correctOrder[index] - 1) 
    }));
    
    // 调试信息 - 输出正确的顺序映射
    console.log('概念:', selectedConcept.name);
    console.log('正确顺序映射:', selectedConcept.correctOrder);
    console.log('碎片与顺序:', fragmentsWithOrder.map(f => ({
      id: f.id,
      text: f.text.substring(0, 15) + (f.text.length > 15 ? '...' : ''),
      originalOrder: f.originalOrder
    })));
    
    // 保存正确的顺序信息，用于提示功能
    const sortedFragments = [...fragmentsWithOrder].sort((a, b) => a.originalOrder - b.originalOrder);
    setCorrectOrder(sortedFragments);
    
    // 然后打乱顺序
    const shuffledFragments = [...fragmentsWithOrder].sort(() => Math.random() - 0.5);
    
    setFragments(shuffledFragments);
    setSelectedFragments([]);
  }, [conceptBank, usedConceptIndices]);

  // 处理碎片点击
  const handleFragmentClick = (fragment) => {
    // 如果碎片已经被选择，则忽略
    if (selectedFragments.some(f => f.id === fragment.id)) return;
    
    // 添加到已选择列表
    const newSelectedFragments = [...selectedFragments, fragment];
    setSelectedFragments(newSelectedFragments);
    
    // 检查是否完成一轮
    if (newSelectedFragments.length === fragments.length) {
      checkResult(newSelectedFragments);
    }
  };
  
  // 清除已选择的碎片
  const handleClearSelection = () => {
    setSelectedFragments([]);
    message.info('已清除所有已选择的碎片');
  };
  
  // 处理位置点击 - 用于新的排序方式
  const handleSlotClick = (slotIndex) => {
    // 如果该位置已有碎片，忽略
    if (selectedFragments.length > slotIndex) return;
    
    // 如果点击的不是下一个要填的位置，忽略
    if (slotIndex !== selectedFragments.length) return;
  };
  
  // 处理显示提示
  const handleToggleHint = () => {
    setShowHint(!showHint);
  };

  // 检查结果
  const checkResult = (selected) => {
    // 调试信息 - 先输出当前的碎片和它们的顺序
    console.log('当前概念:', currentConcept?.name);
    console.log('原始碎片:', fragments.map(f => ({ id: f.id, text: f.text, originalOrder: f.originalOrder })));
    console.log('选择的碎片:', selected.map(f => ({ id: f.id, text: f.text, originalOrder: f.originalOrder })));
    
    // 检查顺序是否正确 - 按照正确的顺序排列
    const isCorrect = selected.every((fragment, index) => {
      // 检查当前位置的碎片的原始顺序是否正确
      const result = fragment.originalOrder === index;
      console.log(`位置 ${index+1}: 期望顺序 ${index}, 实际碎片顺序 ${fragment.originalOrder}, 匹配: ${result ? '✓' : '✗'}`);
      return result;
    });
    
    console.log('最终结果:', isCorrect ? '正确' : '错误');
    
    if (isCorrect) {
      // 成功完成一轮
      const newCompletedRounds = completedRounds + 1;
      setCompletedRounds(newCompletedRounds);
      
      // 每完成一轮就获得一个律迹骰
      setEarnedDice(prevDice => prevDice + 1);
      
      // 通知父组件获得骰子
      onEarnDice(1); // 每轮获得1个骰子
      
      setShowCongrats(true);
      
      // 显示祝贺信息
      Modal.success({
        title: '填写正确',
        content: `恭喜！你成功完成了"${currentConcept?.name}"的拼接，获得了1个律迹骰！`,
        okText: '继续',
      });
      
      // 延迟后隐藏祝贺信息并开始新一轮
      setTimeout(() => {
        setShowCongrats(false);
        
        // 如果已经完成了所有概念或加载已完成，则结束游戏
        if (newCompletedRounds >= conceptBank.length || (isLoadingComplete && newCompletedRounds > 0)) {
          setGameActive(false);
        } else {
          startNewRound();
        }
      }, 2000);
    } else {
      // 失败，重新开始
      message.error('顺序不正确，请重试！');
      setTimeout(() => {
        setSelectedFragments([]);
      }, 1000);
    }
  };

  // 如果没有概念库，显示提示
  if (conceptBank.length === 0) {
    return (
      <div className="legal-concept-puzzle">
        <Title level={4}>正在准备法律概念拼接游戏...</Title>
      </div>
    );
  }

  return (
    <div className="legal-concept-puzzle">
      <AnimatePresence>
        {showCongrats ? (
          <motion.div
            initial={{ opacity: 0, scale: 0.5 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.5 }}
            className="congrats-container"
          >
            <Title level={2} style={{ color: '#1890ff' }}>恭喜！</Title>
            <Text style={{ fontSize: '18px' }}>你获得了 1 个律迹骰</Text>
            <div style={{ marginTop: '20px' }}>
              <AnimatedDice value={1} size={80} />
            </div>
          </motion.div>
        ) : (
          <>
            <div style={{ marginBottom: '20px', textAlign: 'center' }}>
              <Title level={4} style={{ marginBottom: '5px' }}>法律概念拼接游戏</Title>
              <Text>按正确顺序点击下面的碎片，完成法律概念的拼接</Text>
              <div style={{ marginTop: '10px' }}>
                <Text strong>{currentConcept?.name}</Text>
              </div>
              <div style={{ marginTop: '5px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <Text type="secondary">已完成轮数: {completedRounds}</Text>
                  {earnedDice > 0 && (
                    <Text type="success" style={{ marginLeft: '10px' }}>
                      已获得律迹骰: {earnedDice}
                    </Text>
                  )}
                </div>
                {isLoadingComplete && (
                  <Button 
                    type="primary" 
                    size="small" 
                    ghost
                    onClick={handleToggleHint}
                  >
                    {showHint ? '隐藏提示' : '显示提示'}
                  </Button>
                )}
              </div>
            </div>
            
            {/* 定义的空位 */}
            <div className="definition-slots">
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '10px' }}>
                <Text type="secondary">请按顺序填入碎片:</Text>
                <Button 
                  type="default" 
                  size="small" 
                  onClick={handleClearSelection}
                  disabled={selectedFragments.length === 0}
                >
                  清除选择
                </Button>
              </div>
              
              {/* 显示提示信息 */}
              {showHint && (
                <div className="hint-container" style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#fffbe6', border: '1px solid #ffe58f', borderRadius: '4px' }}>
                  <Text type="warning" strong>提示: </Text>
                  <Text type="warning">正确的顺序是: </Text>
                  <div style={{ marginTop: '5px' }}>
                    {correctOrder.map((fragment, index) => (
                      <div key={`hint-${index}`} style={{ padding: '5px', marginBottom: '5px', backgroundColor: 'rgba(255, 229, 143, 0.3)', borderRadius: '2px' }}>
                        <Text mark>{index + 1}. {fragment.text}</Text>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              
              <div className="slots-container">
                {Array.from({ length: fragments.length }).map((_, index) => {
                  const fragment = selectedFragments[index];
                  return (
                    <motion.div
                      key={`slot-${index}`}
                      className={`definition-slot ${fragment ? 'filled' : 'empty'}`}
                      initial={fragment ? { opacity: 0 } : {}}
                      animate={fragment ? { opacity: 1 } : {}}
                    >
                      {fragment ? (
                        <Text strong>{index + 1}. {fragment.text}</Text>
                      ) : (
                        <Text type="secondary">{index + 1}. 点击下方碎片填入...</Text>
                      )}
                    </motion.div>
                  );
                })}
              </div>
            </div>
            
            {/* 可选择的碎片 */}
            <div className="available-fragments">
              <Text type="secondary" style={{ marginBottom: '5px' }}>可用碎片:</Text>
              <div className="fragments-container">
                {fragments
                  .filter(fragment => !selectedFragments.some(f => f.id === fragment.id))
                  .map(fragment => (
                  <motion.div
                    key={`fragment-${fragment.id}`}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    className="fragment"
                    onClick={() => handleFragmentClick(fragment)}
                  >
                    <Text>{fragment.text}</Text>
                  </motion.div>
                ))}
              </div>
            </div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
};

export default LegalConceptPuzzle; 